<template>
  <div class="mt-4">
    <div class="comment_list py-2" v-for="comment in comments" :key="comment.id">
        <CommentItem :comment="comment"/>
    </div>
    <div class="comment_submit mt-5" >
      <h1 class="fw-light">发表评论</h1>
      <Login/>
      <b-form @submit.stop.prevent="submit" v-if="loginUser">
        <b-row>
          <b-col>
            <b-form-textarea
              id="textarea-state"
              v-model="comment"
              :state="commentState"
              @focus="commentFocusHandle"
              placeholder="评论*"
              rows="6"
              class="comment-control fw-light py-2"
            ></b-form-textarea>
            <b-form-invalid-feedback>
              请勿提交空评论
            </b-form-invalid-feedback>
          </b-col>
        </b-row>
        <b-row>
          <b-col class="d-flex justify-content-end">
            <b-btn type="submit" class="submit px-3 py-2 fw-light m-2"
              >发表评论</b-btn
            >
          </b-col>
        </b-row>
      </b-form>
    </div>
  </div>
</template>

<script>
import qs from 'qs'
import CommentItem from './CommentItem.vue'
import Login from './Login'
import { mapState } from 'vuex';
export default {
  name: "Comment",
  components: {
      CommentItem,
      Login,
  },
  props: ['postid'],
  data() {
    return {
      comment: "",
      commentState: null,
      comments: [],
    };
  },

  methods: {
    commentFocusHandle() {
      this.commentState = null;
    },

    checkCommentState(){
      return this.comment !== '';
    },

    resetComment(){
      this.comment = '';
      this.commentState = null;
    },

    submit() {
      this.commentState = this.checkCommentState();
      if(!this.commentState) return;
      const data = {
        username: this.$store.state.loginUser,
        content: this.comment,
        object_id: this.postid,
        content_type: 'post',
      }
      this.$http.post('/comment/comments/', qs.stringify(data)).then(
        res=>{
          console.log(res)
        },
        error=>{
          console.log(error)
        }
      )
      this.getComments()
      this.resetComment()
    },
    getComments(){
      this.$http.get('/comment/comments/' + this.postid).then(
        res=>{
          const { meta, data } = res.data;
          if (meta.code != 200) return console.log(meta.msg);
          const { comments } = data
          this.comments = comments
        },
        error=>{
          console.log(error)
        }
      )
    }
  },

  computed:{
    ...mapState(['loginUser'])
  },

  watch:{
    postid(){
      this.getComments();
    }
  }
};
</script>

<style lang="less" scoped>
.comment-control {
  background-color: #f0f0f0;
}
.comment-control:focus {
  background-color: #f0f0f0;
}
.submit {
  background-color: rgb(208, 66, 44) !important;
  border-radius: 1.5em;
  border: none;
}
.submit:focus {
  -webkit-box-shadow: none;
  box-shadow: none;
}
</style>